package com.ruike.alisurface.ui.payPage;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.ruike.alisurface.BuildConfig;
import com.ruike.alisurface.R;
import com.ruike.alisurface.base.BaseAty;
import com.ruike.alisurface.bean.ShopOrderBean;
import com.ruike.alisurface.https.MchApiHttp;
import com.ruike.alisurface.https.OtherHttp;
import com.ruike.alisurface.utils.CountTimeUtils;
import com.ruike.alisurface.utils.DialogTipUtils;
import com.ruike.alisurface.utils.GsonUtils;
import com.ruike.alisurface.utils.QrcodeUtils;
import com.voodoo.lib_http.ApiListener;
import com.voodoo.lib_logcat.L;
import com.voodoo.lib_utils.imageLoader.GlideImageLoader;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

import static com.ruike.alisurface.https.OtherHttp.GET_ORDER_QR_CODE_URL;

/**
 * Author: voodoo
 * CreateDate: 2023/12/25 025下午 02:45
 * Description: 医保扫码支付
 */
public class PayYiBao_Aty extends BaseAty implements ApiListener {

    @BindView(R.id.payYb_times)
    TextView timesTv;
    @BindView(R.id.payYb_url_qrcode)
    ImageView qrCodeImgv;
    @BindView(R.id.payYb_money_tv)
    TextView moneyTv;

    ShopOrderBean shopOrderBean;//订单信息
    String json;//接收的订单json 数据
    Bitmap mQrCode;//支付二维码的位图

    CountTimeUtils countTimeUtils;
    Timer payTimer;
    TimerTask payTimerTask;
    int mErrorCount;

    @Override
    protected int getLayoutResId() {
        return R.layout.app_pay_yi_bao;
    }

    @Override
    protected void initViews() {
        initTitleBar(false);
        countTimeUtils = new CountTimeUtils(BuildConfig.DEBUG ? 3600 : 300) {
            @Override
            public void onTick(long mMillisUntilFinished) {
                timesTv.setText(String.valueOf(mMillisUntilFinished));
            }

            @Override
            public void onFinish() {
                L.i("onFinish=", "CountTimeUtils#onFinish");
                Bundle bundle = new Bundle();
                bundle.putString("shopOrderBean", json);
                startActivity(ShopPayType_Aty.class, bundle);
                finish();
            }
        };
        countTimeUtils.start();
    }

    @Override
    protected void initData() {
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            json = getIntent().getStringExtra("shopOrderBean");
            shopOrderBean = GsonUtils.fromJson(json.toString(), ShopOrderBean.class);
            if (shopOrderBean != null) {
                showProgressDialog("正在创建订单...");
                OtherHttp.getOrderQrCode(shopOrderBean.getData().getId(), this);
            }
        } else {
            showErrorToast("传入的数据为空");
            bundle = new Bundle();
            bundle.putString("shopOrderBean", json);
            startActivity(ShopPayType_Aty.class, bundle);
            finish();
        }
    }

    void startTimerTask() {
        cancelTimerTask();
        payTimer = new Timer();
        payTimerTask = new TimerTask() {
            @Override
            public void run() {
                MchApiHttp.getPayResult(PayYiBao_Aty.this, shopOrderBean.getData().getId());
            }
        };
        payTimer.schedule(payTimerTask, 3000);
    }

    public void cancelTimerTask() {
        if (payTimer != null) {
            L.i("==cancelTimerTask=取消计时=payTimer=" + payTimer);
            payTimer.cancel();
            payTimer.purge();
            payTimer = null;
        }
        if (payTimerTask != null) {
            L.i("==cancelTimerTask=取消计时=payTimerTask" + payTimerTask);
            payTimerTask.cancel();
            payTimerTask = null;
        }
    }

    @OnClick({R.id.payYb_back})
    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.payYb_back:
                DialogTipUtils.showTipDialog(this, clickView -> {
                    if (DialogTipUtils.xToast != null) {
                        DialogTipUtils.xToast.cancel();
                    }
                    Bundle bundle = new Bundle();
                    bundle.putString("shopOrderBean", json);
                    startActivity(ShopPayType_Aty.class, bundle);
                    finish();
                });
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        cancelTimerTask();
        // 释放数据
        shopOrderBean = null;
        json = null;
        if (mQrCode != null) {
            mQrCode.recycle();
            mQrCode = null;
        }
    }

    @Override
    public void onRequestStart(String requestUrl, int requestId) {

    }

    @Override
    public void onRequestComplete(String requestUrl, int requestId) {

    }

    @Override
    public void onSuccess(String requestUrl, JSONObject requestJson, int requestId) {
        if (GET_ORDER_QR_CODE_URL.contentEquals(requestUrl)) {
            removeProgressDialog();
            shopOrderBean = GsonUtils.fromJson(requestJson.toString(), ShopOrderBean.class);
            mQrCode = QrcodeUtils.createQrCode(shopOrderBean.getData().getUrl());
            GlideImageLoader.getInstance().loadBitmap(this, mQrCode, qrCodeImgv);
            moneyTv.setText(String.format(Locale.ENGLISH, "总金额: %.2f", shopOrderBean.getData().getPay_fee()));
            L.i("订单信息==", shopOrderBean.getData().getDetails());
            startTimerTask();
            return;
        }
        if (requestUrl.endsWith("getPayResult")) {
            cancelTimerTask();
            mErrorCount = 0;
            L.i("payresult=", "支付结果==" + requestJson.toString());
            try {
                JSONObject jsonObject = new JSONObject(json);
                jsonObject.put("payType", "YiBaoPay");
                json = jsonObject.toString();
            } catch (JSONException e) {
                e.printStackTrace();
            }
            doStartActivity(PayShopShipment_Aty.class, json);
        }
    }

    @Override
    public void onError(String requestUrl, String errorMsg, String resultData, int requestId) {
        if (GET_ORDER_QR_CODE_URL.contentEquals(requestUrl)) {
            removeProgressDialog();
            showErrorToast("订单创建失败：" + errorMsg);
            startCountdownTimer(3, null, null);
            return;
        }
        if (requestUrl.endsWith("getPayResult")) {
            mErrorCount++;
            L.i("payresult=", "查询次数==" + mErrorCount + "支付结果==" + errorMsg);
            startTimerTask();
        }
    }

}
